package com.gin.no_gay_alliance.manager;

import android.util.Log;

import androidx.annotation.NonNull;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gin.nga.callback.JsonCallback;
import com.gin.nga.client.NgaClient;
import com.gin.nga.exception.NgaException;
import com.gin.nga.method.NukeApi;
import com.gin.nga.method.PostApi;
import com.gin.nga.params.post.PrepareParam;
import com.gin.nga.response.body.nuke.TopicKeys;
import com.gin.nga.response.post.PrepareBody;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Bundle;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.callback.RequestCallback;
import com.gin.no_gay_alliance.utils.DataStoreUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;

/**
 * 发帖管理器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/16 14:28
 **/
public class PostManager {
    public static final String TAG = PostManager.class.getSimpleName();
    public static final String DATA_STORE_NAME = "POST_TEMPORARY_STORAGE";
    /**
     * 缓存对象:主题分类
     */
    private final HashMap<Long, Bundle<TopicKeys>> topicKeyCache = new HashMap<>();

    /**
     * 发送准备请求
     *
     * @param prepareParam 准备参数
     * @param callback     回调
     */
    public void prepare(PrepareParam prepareParam, Callback<PrepareBody> callback) {
        PostApi.prepare(MyApplication.getClient(), prepareParam).async(new RequestCallback<>(callback));
    }


    public void getTopicKey(boolean ignoreCache, long forumId, Callback<TopicKeys> callback) {
        // 检查缓存
        if (Bundle.checkCache(ignoreCache, topicKeyCache, forumId, callback)) {
            return;
        }
        callback.beforeRequest();

        NgaClient client = MyApplication.getClient();
        NukeApi.topicKeyList(client, forumId).async(new JsonCallback<TopicKeys>() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                callback.onFailure(call, e);
            }

            @Override
            public void onSuccess(TopicKeys body) {
                Bundle<TopicKeys> bundle = new Bundle<>(body, 30, TimeUnit.MINUTES);
                topicKeyCache.put(forumId, bundle);
                callback.onSuccess(body);
            }

            @Override
            public void handleException(NgaException e) {
                callback.handleException(e);
            }
        });
    }

    /**
     * 暂存回复标题和正文
     *
     * @param param   准备参数
     * @param title   标题
     * @param content 正文
     */
    public void saveTempData(PrepareParam param, String title, String content) {
        long userId = MyApplication.getClient().getUserId();
        DataStoreUtils instance = DataStoreUtils.getInstance(DATA_STORE_NAME);
        instance.set(getTempTitleKey(param, userId), title);
        instance.set(getTempContentKey(param, userId), content);
    }

    /**
     * 获取暂存的标题和正文
     *
     * @param param 准备参数
     * @return 标题和正文
     */
    public TempData getTempData(PrepareParam param) {
        long userId = MyApplication.getClient().getUserId();
        DataStoreUtils instance = DataStoreUtils.getInstance(DATA_STORE_NAME);
        String title = instance.get(getTempTitleKey(param, userId), "");
        String content = instance.get(getTempContentKey(param, userId), "");
        if (!"".equals(content)) {
            Log.d(TAG, "找到发帖数据: " + toStringPrepareParam(param));
            return new TempData(title, content);
        }
        return null;
    }

    /**
     * 移除暂存数据
     *
     * @param param 标题和正文
     */
    public void removeTempData(PrepareParam param) {
        long userId = MyApplication.getClient().getUserId();
        DataStoreUtils instance = DataStoreUtils.getInstance(DATA_STORE_NAME);
        instance.remove(getTempTitleKey(param, userId), "");
        instance.remove(getTempContentKey(param, userId), "");
    }

    /**
     * 清空暂存数据
     */
    public void clearTempData() {
        DataStoreUtils.getInstance(DATA_STORE_NAME).clear();
    }

    /**
     * 返回暂存数据占用空间
     *
     * @return 文件大小(字节)
     */
    public long size() {
        return DataStoreUtils.size(DATA_STORE_NAME);
    }

    /**
     * 保存标题的key
     *
     * @param param  准备参数
     * @param userId
     * @return key
     */
    private static String getTempTitleKey(PrepareParam param, long userId) {
        return String.format("%s_%s_%s", userId, "TITLE", toStringPrepareParam(param));
    }

    /**
     * 保存正文的key
     *
     * @param param  准备参数
     * @param userId
     * @return key
     */
    private static String getTempContentKey(PrepareParam param, long userId) {
        return String.format("%s_%s_%s", userId, "CONTENT", toStringPrepareParam(param));
    }

    /**
     * 准备参数序列化,用于datastore的key
     *
     * @param param 准备参数
     * @return
     */
    private static String toStringPrepareParam(PrepareParam param) {
        try {
            return new ObjectMapper().writeValueAsString(param);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static class TempData {
        public String title;
        public String content;

        public TempData(String title, String content) {
            this.title = title;
            this.content = content;
        }
    }
}
